<template>
   <div class="app-container">
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
         <el-form-item label="部门名称" prop="deptName">
            <el-input v-model="queryParams.deptName" placeholder="请输入部门名称" clearable style="width: 200px"
               @keyup.enter="handleQuery" />
         </el-form-item>
         <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="部门状态" clearable style="width: 200px">
               <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
         </el-form-item>
         <el-form-item>
            <el-button color="#265DA4" :dark="isDark" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
         </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
         <el-col :span="1.5">
            <el-button color="#265DA4" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:dept:add']">新增</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button type="info" plain icon="Sort" @click="toggleExpandAll">展开/折叠</el-button>
         </el-col>
         <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-if="refreshTable" v-loading="loading" :data="deptList" row-key="deptId" :default-expand-all="isExpandAll"
         :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
         <el-table-column prop="deptName" label="部门名称"></el-table-column>
         <el-table-column prop="orderNum" label="排序" width="200"></el-table-column>
         <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
               <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
            </template>
         </el-table-column>
         <el-table-column label="创建时间" align="left" prop="createTime" width="200">
            <template #default="scope">
               <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
         </el-table-column>
         <el-table-column label="操作" align="left" class-name="small-padding fixed-width">
            <template #default="scope">
               <el-button link style="color:#265DA4;" icon="Edit" @click="handleUpdate(scope.row)"
                  v-hasPermi="['system:dept:edit']">修改</el-button>
               <el-button link style="color:#265DA4;" icon="Plus" @click="handleAdd(scope.row)"
                  v-hasPermi="['system:dept:add']">新增</el-button>
               <el-button v-if="scope.row.parentId != 0" link color="#265DA4" icon="Delete"
                  @click="handleDelete(scope.row)" v-hasPermi="['system:dept:remove']">删除</el-button>
            </template>
         </el-table-column>
      </el-table>

      <!-- 添加或修改部门对话框 -->
      <el-dialog :title="title" v-model="open" width="650px" append-to-body class="dialogClass" close-icon="CloseBold">
         <template #title>
            <span>{{ title }}</span>
         </template>
         <div class="dialog_box">
            <el-form ref="deptRef" :model="form" :rules="rules" label-width="80px">
               <el-row class="dept_box">
                  <el-col :span="24">
                     <div class="title" @click="handleExpend('dept')">部门信息<el-icon>
                           <CaretBottom color="#2B5AA2" />
                        </el-icon></div>
                  </el-col>
                  <el-row v-show="expend.dept">
                     <el-col :span="24" v-if="form.parentId !== 0">
                        <el-form-item label="上级部门" prop="parentId">
                           <el-tree-select v-model="form.parentId" :data="deptOptions"
                              :props="{ value: 'deptId', label: 'deptName', children: 'children' }" value-key="deptId"
                              placeholder="选择上级部门" check-strictly />
                        </el-form-item>
                     </el-col>
                     <el-col :span="12">
                        <el-form-item label="部门名称" prop="deptName">
                           <el-input v-model="form.deptName" placeholder="请输入部门名称" />
                        </el-form-item>
                     </el-col>
                     <el-col :span="12">
                        <el-form-item label="显示排序" prop="orderNum">
                           <el-input-number v-model="form.orderNum" controls-position="right" :min="0" />
                        </el-form-item>
                     </el-col>
                     <el-col :span="12">
                        <el-form-item label="负责人" prop="leader">
                           <el-input v-model="form.leader" placeholder="请输入负责人" maxlength="20" />
                        </el-form-item>
                     </el-col>
                     <el-col :span="12">
                        <el-form-item label="联系电话" prop="phone">
                           <el-input v-model="form.phone" placeholder="请输入联系电话" maxlength="11" />
                        </el-form-item>
                     </el-col>
                     <el-col :span="12">
                        <el-form-item label="邮箱" prop="email">
                           <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
                        </el-form-item>
                     </el-col>
                     <el-col :span="12">
                        <el-form-item label="部门状态">
                           <el-radio-group v-model="form.status">
                              <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.value">{{
                                 dict.label
                              }}</el-radio>
                           </el-radio-group>
                        </el-form-item>
                     </el-col>
                     <el-col :span="24">
                        <el-form-item label="部门类型" prop="email">
                           <el-select v-model="form.deptType" placeholder="请选择" style="width: 150px;">
                              <el-option v-for="dict in deptTypeList" :key="dict.dictCode" :label="dict.dictLabel"
                                 :value="dict.dictCode"></el-option>
                           </el-select>
                           <!-- <el-cascader :options="options" /> -->
                           <el-select v-model="form.deptLevel" placeholder="请选择" style="width: 150px;">
                              <el-option v-for="dict in stationTypeList" :key="dict.dictCode" :label="dict.dictLabel"
                                 :value="dict.dictCode"></el-option>
                           </el-select>
                           <el-select v-model="form.stationType" placeholder="请选择" style="width: 150px;">
                              <el-option v-for="dict in deptLevelList" :key="dict.dictCode" :label="dict.dictLabel"
                                 :value="dict.dictCode"></el-option>
                           </el-select>
                        </el-form-item>
                     </el-col>
                     <el-col :span="12" class="inputFlex">
                        <el-form-item label="部门地址" prop="status">
                           <el-input v-model="form.address" placeholder="部门地址" maxlength="50"
                              style="width: 170px;margin-right:10px;" />
                           <span style="color: #2B5AA2;font-size: 12px;" @click="handleSelete('address', 'text')"><el-icon>
                                 <Location />
                              </el-icon>选择</span>
                        </el-form-item>
                     </el-col>
                  </el-row>
               </el-row>
            </el-form>
            <el-form label-width="100px">
               <el-row class="dept_box">
                  <el-col :span="24">
                     <div class="title" @click="handleExpend('area')">辖区信息
                        <el-icon>
                           <CaretBottom color="#2B5AA2" />
                        </el-icon>
                     </div>
                  </el-col>
                  <el-row v-show="expend.area">
                     <el-row v-for="(item, index) in areaInfos" :key="index">
                        <el-col :span="24">
                           <el-form-item label="管辖区域名称" prop="areaName">
                              <el-input v-model="item.areaName" placeholder="管辖区域名称" maxlength="50"
                                 style="width:200px; margin-right: 10px;" />
                              <span style="color: #2B5AA2;font-size: 12px;" @click="handleSelete('area', 'text')">
                                 <el-icon>
                                    <Location />
                                 </el-icon>
                                 选择
                              </span>
                           </el-form-item>
                        </el-col>
                     </el-row>
                     <el-col :span="24">
                        <el-form-item label="管辖区域绘图" prop="areaName">
                           <el-input v-model="form.areaName" placeholder="管辖区域绘图" maxlength="50"
                              style="width:200px; margin-right: 10px;" />
                           <span style="color: #2B5AA2;font-size: 12px;" @click="handleSelete('area', 'draw')">
                              <el-icon>
                                 <Location />
                              </el-icon>
                              绘图
                           </span>
                        </el-form-item>
                     </el-col>
                     <!-- <el-col :span="14" class="inputFlex">
                           <el-form-item label="经纬度" prop="status">
                              <el-input v-model="item.areaLongitude" placeholder="经度" maxlength="50" style="width: 80px;" />
                              <el-input v-model="item.areaLatitude" placeholder="纬度" maxlength="50"
                                 style="width: 80px; margin-right: 10px;" />
                           </el-form-item>
                           <span style="color: #2B5AA2;font-size: 12px;" @click="handleAddItem('area')"><el-icon>
                                 <Plus />
                              </el-icon>新增</span>
                        </el-col> -->

                  </el-row>
               </el-row>
            </el-form>
            <el-form label-width="100px">
               <el-row class="dept_box">
                  <el-col :span="24">
                     <div class="title" @click="handleExpend('traffic')">辖区交通
                        <el-icon>
                           <CaretBottom color="#2B5AA2" />
                        </el-icon>
                     </div>
                  </el-col>
                  <el-row v-show="expend.traffic">
                     <el-row v-for="(item, index) in unitInfos" :key="index">
                        <el-col :span="24">
                           <el-form-item label="管辖区域名称" prop="unitName">
                              <el-input v-model="item.unitName" placeholder="管辖区域名称" maxlength="50"
                                 style="width:200px;  margin-right: 10px;" />
                              <span style="color: #2B5AA2;font-size: 12px;"
                                 @click="handleSelete('traffic', 'text')"><el-icon>
                                    <Location />
                                 </el-icon>选择</span>
                           </el-form-item>
                        </el-col>
                     </el-row>
                     <el-col :span="24">
                        <el-form-item label="管辖区域绘图" prop="unitName">
                           <el-input v-model="form.unitName" placeholder="管辖区域绘图" maxlength="50"
                              style="width:200px;  margin-right: 10px;" />
                           <span style="color: #2B5AA2;font-size: 12px;" @click="handleSelete('traffic', 'draw')"><el-icon>
                                 <Location />
                              </el-icon>绘图</span>
                        </el-form-item>
                     </el-col>
                     <!-- <el-col :span="14" class="inputFlex">
                           <el-form-item label="经纬度" prop="status">
                              <el-input v-model="item.unitLongitude" placeholder="经度" maxlength="50" style="width: 80px;" />
                              <el-input v-model="item.unitLatitude" placeholder="纬度" maxlength="50"
                                 style="width: 80px;margin-right: 10px;" />
                           </el-form-item>
                           <span style="color: #2B5AA2;font-size: 12px;" @click="handleAddItem('area')"><el-icon>
                                 <Plus />
                              </el-icon>新增</span>
                        </el-col> -->

                  </el-row>
               </el-row>
            </el-form>
            <el-form :model="form3" :rules="rules" label-width="80px">
               <el-row class="dept_box">
                  <el-col :span="24">
                     <div class="title">通信频道<el-icon>
                           <CaretBottom color="#2B5AA2" />
                        </el-icon></div>
                  </el-col>
                  <el-row v-show="expend.communicae">
                     <el-col :span="24">
                        <el-form-item label="频 道" prop="channel">
                           <el-input v-model="form3.channel" placeholder="请输入频道" maxlength="50" />
                        </el-form-item>
                     </el-col>
                  </el-row>
               </el-row>
            </el-form>
            <!-- <el-row class="dept_box">
               <el-col :span="24" class="cartBox">
                  <div class="title">
                     车辆信息
                     <el-button color="#265DA4" @click="handleCart">设 置</el-button>
                  </div>

               </el-col>
            </el-row> -->
            <el-form label-width="80px" :rule="cartRules">
               <el-row class="dept_box">
                  <el-col :span="24" class="cartBox">
                     <div class="title" @click="handleExpend('cart')">车辆信息<el-icon>
                           <CaretBottom color="#2B5AA2" />
                        </el-icon></div>
                     <span class="btnright" @click="handleAddItem('cart')"><el-icon>
                           <Plus />
                        </el-icon>新增</span>
                  </el-col>
                  <el-row v-show="expend.cart">
                     <el-row v-for="(item, index) in deptCars" :key="index">
                        <el-row>
                           <el-col :span="24">
                              <div class="title title1">车辆基本情况</div>
                           </el-col>
                           <el-col :span="8">
                              <el-form-item label="车辆名称" prop="carName">
                                 <el-input v-model="item.carName" placeholder="请输入频道" maxlength="50" />
                              </el-form-item>
                           </el-col>
                           <el-col :span="8">
                              <el-form-item label="车牌号" prop="licenseNumber">
                                 <el-input v-model="item.licenseNumber" placeholder="请输入车牌号" maxlength="50" />
                              </el-form-item>
                           </el-col>
                           <el-col :span="8">
                              <el-form-item label="车 型" prop="carType">
                                 <el-select v-model="item.carType" placeholder="请选择" style="width: 150px;">
                                    <el-option v-for="dict in cartLevelList" :key="dict.dictCode" :label="dict.dictLabel"
                                       :value="dict.dictCode"></el-option>
                                 </el-select>
                              </el-form-item>
                           </el-col>
                           <el-col :span="12">
                              <el-form-item label="手台泵" prop="handPump">
                                 <el-input v-model="item.handPump" placeholder="请输入" maxlength="50" />
                              </el-form-item>
                           </el-col>
                           <el-col :span="12">
                              <el-form-item label="泵流量" prop="pumpFlow">
                                 <el-input v-model="item.pumpFlow" placeholder="请输入" maxlength="50"
                                    style="width: 100px; margin-right: 10px;" />升/秒
                              </el-form-item>
                           </el-col>
                           <el-col :span="12">
                              <el-form-item label="消防炮" prop="gunFlow">
                                 <el-input v-model="item.gunFlow" placeholder="请输入频道" maxlength="50"
                                    style="width: 150px;margin-right: 10px;" />升/秒
                              </el-form-item>
                           </el-col>
                           <el-col :span="12">
                              <el-form-item label="举升高度" prop="liftingHeight">
                                 <el-input v-model="item.liftingHeight" placeholder="请输入频道" maxlength="50"
                                    style="width: 100px;margin-right: 10px;" />米
                              </el-form-item>
                           </el-col>
                        </el-row>
                        <el-row>
                           <el-col :span="24">
                              <div class="title title1">哉流量</div>
                           </el-col>
                           <el-col :span="8">
                              <el-form-item label="载水量">
                                 <el-input v-model="item.carryingWater" placeholder="请输入" maxlength="50"
                                    style="width: 80px;margin-right: 10px;" />吨
                              </el-form-item>
                           </el-col>
                           <el-col :span="8">
                              <el-form-item label="泡沫量">
                                 <el-input v-model="item.foamContent" placeholder="请输入" maxlength="50"
                                    style="width: 80px;margin-right: 10px;" />吨
                              </el-form-item>
                           </el-col>
                           <el-col :span="8">
                              <el-form-item label="泡沫类型">
                                 <el-select v-model="item.foamType" placeholder="请选择" style="width: 150px;">
                                    <el-option v-for="dict in formLevelList" :key="dict.dictCode" :label="dict.dictLabel"
                                       :value="dict.dictCode"></el-option>
                                 </el-select>
                              </el-form-item>
                           </el-col>
                        </el-row>
                        <el-row>
                           <el-col :span="24">
                              <div class="title title1">抢险救援</div>
                           </el-col>
                           <el-col :span="12">
                              <el-form-item label="牵 引">
                                 <el-input v-model="item.tractionPower" placeholder="请输入" maxlength="50"
                                    style="width: 120px;margin-right: 10px;" />吨
                              </el-form-item>
                           </el-col>
                           <el-col :span="12">
                              <el-form-item label="吊 机">
                                 <el-input v-model="item.overhangPower" placeholder="请输入" maxlength="50"
                                    style="width: 120px;margin-right: 10px;" />吨
                              </el-form-item>
                           </el-col>
                        </el-row>
                        <el-row>
                           <el-col :span="12">
                              <div class="title title1">备注</div>
                           </el-col>
                           <el-col :span="24">
                              <el-form-item label="备 注">
                                 <el-input type="textarea" v-model="item.remark" placeholder="请输入" maxlength="50" />
                              </el-form-item>
                           </el-col>
                        </el-row>
                     </el-row>
                  </el-row>
               </el-row>
            </el-form>
         </div>
         <template #footer>
            <div class="dialog-footer">
               <el-button color="#265DA4" @click="submitForm">确 定</el-button>
               <el-button @click="cancel">取 消</el-button>
            </div>
         </template>
      </el-dialog>
      <!-- 车辆信息 -->
      <!-- <el-dialog title="车辆信息" v-model="openCart" width="650px" append-to-body class="dialogClass" close-icon="CloseBold">
         <div class="dialog_box">
            <el-form label-width="80px">
               <el-row class="dept_box">
                  <el-col :span="24" class="cartBox">
                     <div class="title" @click="handleExpend('cart')">车辆信息
                        <el-icon>
                           <CaretBottom color="#2B5AA2" />
                        </el-icon>
                     </div>
                     <span class="btnright" @click="handleAddItem('cart')"><el-icon>
                           <Plus />
                        </el-icon>新增</span>
                  </el-col>
                  <el-row>
                     <el-row v-for="(item, index) in deptCars" :key="index">
                        <el-row>
                           <el-col :span="24">
                              <div class="title title1">车辆基本情况</div>
                           </el-col>
                           <el-col :span="8">
                              <el-form-item label="车辆名称" prop="carName">
                                 <el-input v-model="item.carName" placeholder="请输入频道" maxlength="50" />
                              </el-form-item>
                           </el-col>
                           <el-col :span="8">
                              <el-form-item label="车牌号" prop="licenseNumber">
                                 <el-input v-model="item.licenseNumber" placeholder="请输入车牌号" maxlength="50" />
                              </el-form-item>
                           </el-col>
                           <el-col :span="8">
                              <el-form-item label="车 型" prop="carType">
                                 <el-select v-model="item.carType" placeholder="请选择" style="width: 150px;">
                                    <el-option v-for="dict in cartLevelList" :key="dict.dictCode" :label="dict.dictLabel"
                                       :value="dict.dictCode"></el-option>
                                 </el-select>
                              </el-form-item>
                           </el-col>
                           <el-col :span="12">
                              <el-form-item label="手台泵" prop="handPump">
                                 <el-input v-model="item.handPump" placeholder="请输入" maxlength="50" />
                              </el-form-item>
                           </el-col>
                           <el-col :span="12">
                              <el-form-item label="泵流量" prop="pumpFlow">
                                 <el-input v-model="item.pumpFlow" placeholder="请输入" maxlength="50"
                                    style="width: 100px; margin-right: 10px;" />升/秒
                              </el-form-item>
                           </el-col>
                           <el-col :span="12">
                              <el-form-item label="消防炮" prop="gunFlow">
                                 <el-input v-model="item.gunFlow" placeholder="请输入频道" maxlength="50"
                                    style="width: 150px;margin-right: 10px;" />升/秒
                              </el-form-item>
                           </el-col>
                           <el-col :span="12">
                              <el-form-item label="举升高度" prop="liftingHeight">
                                 <el-input v-model="item.liftingHeight" placeholder="请输入频道" maxlength="50"
                                    style="width: 100px;margin-right: 10px;" />米
                              </el-form-item>
                           </el-col>
                        </el-row>
                        <el-row>
                           <el-col :span="24">
                              <div class="title title1">哉流量</div>
                           </el-col>
                           <el-col :span="8">
                              <el-form-item label="载水量">
                                 <el-input v-model="item.carryingWater" placeholder="请输入" maxlength="50"
                                    style="width: 80px;margin-right: 10px;" />吨
                              </el-form-item>
                           </el-col>
                           <el-col :span="8">
                              <el-form-item label="泡沫量">
                                 <el-input v-model="item.foamContent" placeholder="请输入" maxlength="50"
                                    style="width: 80px;margin-right: 10px;" />吨
                              </el-form-item>
                           </el-col>
                           <el-col :span="8">
                              <el-form-item label="泡沫类型">
                                 <el-select v-model="item.foamType" placeholder="请选择" style="width: 150px;">
                                    <el-option v-for="dict in formLevelList" :key="dict.dictCode" :label="dict.dictLabel"
                                       :value="dict.dictCode"></el-option>
                                 </el-select>
                              </el-form-item>
                           </el-col>
                        </el-row>
                        <el-row>
                           <el-col :span="24">
                              <div class="title title1">抢险救援</div>
                           </el-col>
                           <el-col :span="12">
                              <el-form-item label="牵 引">
                                 <el-input v-model="item.tractionPower" placeholder="请输入" maxlength="50"
                                    style="width: 120px;margin-right: 10px;" />吨
                              </el-form-item>
                           </el-col>
                           <el-col :span="12">
                              <el-form-item label="吊 机">
                                 <el-input v-model="item.overhangPower" placeholder="请输入" maxlength="50"
                                    style="width: 120px;margin-right: 10px;" />吨
                              </el-form-item>
                           </el-col>
                        </el-row>
                        <el-row>
                           <el-col :span="12">
                              <div class="title title1">备注</div>
                           </el-col>
                           <el-col :span="24">
                              <el-form-item label="备 注">
                                 <el-input type="textarea" v-model="item.remark" placeholder="请输入" maxlength="50" />
                              </el-form-item>
                           </el-col>
                        </el-row>
                     </el-row>
                  </el-row>
               </el-row>
            </el-form>
         </div>
         <template #footer>
            <div class="dialog-footer">
               <el-button color="#265DA4" @click="submitCart">确 定</el-button>
               <el-button @click="cancelCart">取 消</el-button>
            </div>
         </template>
      </el-dialog> -->

      <!-- 地图选择 -->
      <el-dialog title="区域选择" v-model="openMap" width="780px" append-to-body ref="contentBox">
         <el-col :span="10">
            <div class="inputBox">
               <span>区域：</span>
               <input id="tipinput" placeholder="请输入地址查询" />
            </div>
         </el-col>
         <div id="container"></div>
         <div class="mark">*请在地图上标绘，（单击地图即可绘制,双击鼠标左键可结束绘制）<el-button type="primary" @click="handleEditDraw">重绘</el-button>
         </div>
         <template #footer>
            <div class="dialog-footer">
               <el-button color="#265DA4" @click="submitMap">确 定</el-button>
               <el-button @click="cancelMap">取 消</el-button>
            </div>
         </template>
      </el-dialog>

      <!-- 自定义信息弹框 -->
      <div class="windowBox" v-show="windowVisible" ref="chatbox" @mousedown="dragx($event)">
         <div class="title">
            <span>请填写管辖区域</span>
         </div>
         <!-- </template> -->
         <div class="item" v-for="(item, index) in answerList" :key="index">
            <span>{{ index + 1 }}、{{ item }}</span>
            <span class="close" @click="handleDeleteAnwser(index)">删除</span>
         </div>
         <div class="btnBox" v-show="showBtn">
            <el-input type="text" v-model="anserValue" placeholder="请输入答案"></el-input>
            <el-button size="mini" style="background: linear-gradient(180deg, #4780F2 0%, #2B5AA2 100%);color: #fff;"
               @click="canfirmWindow">确定</el-button>
            <el-button size="mini" style="border: 1px solid #2B5AA2;" @click="cacelWindow">
               取消
            </el-button>
         </div>
         <div class="addBtn" @click="addItem">
            + 添加选项
         </div>
      </div>
   </div>
</template>

<script setup name="Dept">
import AMapLoader from "@amap/amap-jsapi-loader";

import { toRefs } from 'vue'
import { listDept, getDept, delDept, addDept, updateDept, listDeptExcludeChild, addByArr } from "@/api/system/dept";
import { listData } from "@/api/system/dict/data";

const { proxy } = getCurrentInstance();
const { sys_normal_disable } = proxy.useDict("sys_normal_disable");

const deptList = ref([]);
const open = ref(false);
const openMap = ref(false)
const loading = ref(true);
const showSearch = ref(true);
const title = ref("");
const deptOptions = ref([]);
const deptTypeList = ref([]);
const stationTypeList = ref([]);
const deptLevelList = ref([]);
const formLevelList = ref([]);
const cartLevelList = ref([]);
const isExpandAll = ref(true);
const refreshTable = ref(true);
const windowVisible = ref(false)
const openCart = ref(false)
const contentBox = ref(null)
const chatbox = ref(null);
const map = ref(null)
let anserValue = ref('')
let answerList = ref([])
let showBtn = ref(true)
const mapAddressList = ref({});
const overlays = ref([])



const expend = reactive({
   dept: true,
   area: true,
   traffic: true,
   communicae: true,
   cart: false,

})
const drawData = {
   drawtype: '',
   drawvalue: '',
}
const drawItem = ref('')
const areaPlotData = ref('')// 区域绘图的经纬度
const unitPlotData = ref('') // 区域交通的经纬度
const data = reactive({
   form: {}, //部门信息
   queryParams: {
      deptName: undefined,
      status: undefined
   },
   rules: {
      parentId: [{ required: true, message: "上级部门不能为空", trigger: "blur" }],
      deptName: [{ required: true, message: "部门名称不能为空", trigger: "blur" }],
      orderNum: [{ required: true, message: "显示排序不能为空", trigger: "blur" }],
      email: [{ type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }],
      phone: [{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }]
   },
   areaInfos: [{ // 部门辖区
      areaName: '',
      // areaLongitude: '',
      // areaLatitude: '',
   }],
   unitInfos: [{ // 辖区交通
      unitName: '',
      // unitLongitude: '',
      // unitLatitude: '',
   }],
   form3: {
      channel: ''
   },
   deptCars: [{
      carName: "", // 车辆名称
      licenseNumber: "", // 车牌号码
      // frameNumber: "WDAYLK9699L434185", // 车架号码
      carType: "", // 车型
      // equippingTime: "2023-10-23 11:23:22", // 装备时间
      // tradeId: "奔驰", // 厂商ID
      handPump: "", // 手抬泵数量
      carryingWater: "", //载水量
      foamContent: "", //泡沫量
      foamType: "", //泡沫类型
      pumpFlow: "", //泵流量
      liftingHeight: "", //举升高度
      gunFlow: "", //消防炮流量
      tractionPower: "", //牵引
      overhangPower: "", //吊机
      remark: '', //备注
      // vehicleEquipment: "上面有一个皮卡丘" //车载器材
   }],
   cartRules: {
      carName: [{ required: true, message: "车辆名称不能为空", trigger: "blur" }],
      licenseNumber: [{ required: true, message: "车牌号码不能为空", trigger: "blur" }],
      carType: [{ required: true, message: "车型不能为空", trigger: "blur" }],

   },
});

const { queryParams, form, rules, areaInfos, unitInfos, form3, deptCars, cartRules } = toRefs(data);




function dragx(el) {
   let oDiv = chatbox.value; //当前元素
   // 计算鼠标位置相对于元素的偏移量,clientX:元素的x轴坐标,offsetLeft元素相对于x轴左边的距离
   console.log(el.clientX, 'el.clientX', oDiv.offsetLeft);
   let disX = el.clientX - oDiv.offsetLeft;
   let disY = el.clientY - oDiv.offsetTop;
   let contBox = contentBox.value
   document.onmousemove = function (e) {
      //通过事件委托，计算移动的距离
      let l = e.clientX - disX;
      let t = e.clientY - disY;

      if (l < 0) {
         //如果左侧的距离小于0，就让距离等于0.不能超出地图左侧。如果需要磁性吸附，把0改为100或者想要的数字即可
         l = 0;
      } else if (l > contBox.clientWidth - oDiv.offsetWidth) {
         //如果左侧的距离>地图的宽度-元素的宽度。也就是说元素的右侧超出地图的右侧，就让元素的右侧在地图的右侧上
         l = contBox.clientWidth - oDiv.offsetWidth;
      }
      if (t < 0) {
         //和左右距离同理
         t = 0;
      } else if (t > contBox.clientHeight - oDiv.offsetHeight) {
         t = contBox.clientHeight - oDiv.offsetHeight;
      }
      //移动当前元素
      oDiv.style.left = l + "px";
      oDiv.style.top = t + "px";
   };
   document.onmouseup = function (e) {
      document.onmousemove = null;
      document.onmouseup = null;
   };
   // 解决有些时候,在鼠标松开的时候,元素仍然可以拖动;
   document.ondragstart = function (ev) {
      ev.preventDefault();
   };
   document.ondragend = function (ev) {
      ev.preventDefault();
   };
   return false;
};
function handleDeleteAnwser(index) {
   answerList.value.splice(index, 1)
}
// 重绘
function handleEditDraw() {
   map.value.clearMap();
   overlays.value = []
}
// 初始化地图
function initMap(type, value) {
   drawData.drawtype = type
   drawData.drawvalue = value
   map.value = new AMap.Map("container", {
      resizeEnable: true, //是否监控地图容器尺寸变化
      zoom: 11, //初始化地图层级
      city: '杭州',
      // center: [116.397428, 39.90923], //初始化地图中心点
      plugins: ["AMap.AutoComplete", "AMap.PlaceSearch", "AMap.MouseTool"],
   });
   //输入提示
   AMap.plugin(['AMap.Autocomplete', 'AMap.PlaceSearch'], function () {
      var autoOptions = {
         input: "tipinput",
      };
      var auto = new AMap.Autocomplete(autoOptions);
      const placeSearch = new AMap.PlaceSearch({
         map: map.value
      })
      const geocoder = new AMap.Geocoder({
         radius: 1000,
         extensions: "all",
      });
      //构造地点查询类
      console.log(auto, 'auto1', proxy.$refs);
      AMap.event.addListener(auto, "select", function (data) {
         console.log(data, "data000");

         let { poi } = data
         if (type === 'address') {
            form.value.address = poi.name
            form.value.longitude = poi.location.lng
            form.value.latitude = poi.location.lat
         }
         console.log(form.value, 'form.value');

         placeSearch.setCity(data.poi.adcode);
         placeSearch.search(data.poi.name); //关键字查询查询
         form.value.adcode = data.poi.adcode
         var opts = {
            subdistrict: 1, //获取边界不需要返回下级行政区
            extensions: "base", //返回行政区边界坐标组等具体信息 ,,base:不用返回，all：返回
            level: "district", //查询行政级别为 区
         };
         let district = new AMap.DistrictSearch(opts);
         district.search(data.poi.adcode, function (status, result) {
            console.log(result, 'result');
            form.value.adname = result.districtList[0].name
         })

      }); //注册监听，当选中某条记录时会触发
   });

   if (value === 'draw') {
      console.log(overlays.value, 'overlays.value-kkkkkkk');
      //   画区域工具
      var mouseTool = new AMap.MouseTool(map.value)
      mouseTool.on('draw', function (event) {
         // event.obj 为绘制出来的覆盖物对象
         console.log('覆盖物对象绘制完成', event)
         let points = event.obj.getPath()
         console.log(points, 'points1111');

         if (type === 'area') {
            // for (var i = 0; i < points.length; i++) {
            overlays.value.push(points);
            // }
            var polygon1 = new AMap.Polygon({
               path: overlays.value,
               strokeColor: "#409EFF",
               strokeWeight: 6,
               strokeOpacity: 0.2,
               fillOpacity: 0.4,
               fillColor: '#1791fc',
               zIndex: 50,
               bubble: true,
            })
            map.value.add([polygon1])

         } else if (type === 'traffic') {
            overlays.value.push(points)
         }

         console.log(overlays.value, 'overlays1111');

      })

      function draw() {
         mouseTool.polyline({
            strokeColor: '#409EFF',
            strokeWeight: 8,
            //同Polyline的Option设置
         });

      }
      draw()

      console.log('value00999', areaPlotData.value);
      // 编辑时将数据赋上去
      var lineStyle = {
         isOutline: true,
         outlineColor: '#409EFF',
         borderWeight: 1,
         strokeColor: "#409EFF",
         strokeOpacity: 1,
         strokeWeight: 6,
         strokeStyle: "solid",
         lineJoin: 'round',
         lineCap: 'round',
         zIndex: 50,

      }
      var polyline = null
      var data = null
      if (type === 'area' && title.value == '修改部门') {

         overlays.value = areaPlotData.value || []
         data = areaPlotData.value || []
         console.log(data,'data');
         // data.forEach((item)=>{
         // console.log(item,'item');
           let polyline = new AMap.Polyline({
               path: item,
               ...lineStyle
            })
            map.value.add([polyline]);
         // })



         map.value.setFitView();
      } else if (type === 'traffic' && title.value == '修改部门') {
         overlays.value = unitPlotData.value || []
         data = unitPlotData.value || []

         for (let i = 0; i < data.length; i++) {
            polyline = new AMap.Polyline({
               path: data[i],
               ...lineStyle
            })
            map.value.add([polyline]);
            map.value.setFitView();
         }
      }
      console.log(data, 'data888');
   } else {
      if (type === 'area' || type === 'traffic') {
         windowVisible.value = true;
         // 编辑时将数据弄上去
         if (type === 'area' && title.value == '修改部门') {
            answerList.value = areaInfos.value.map(item => {
               return item.areaName
            })
         } else if (type === 'traffic' && title.value == '修改部门') {
            answerList.value = unitInfos.value.map(item => {
               return item.unitName
            })
         }
      }
   }

}
const canfirmWindow = () => {
   if (!anserValue.value) {
      ElMessage.warning('请先填写答案')
   }
   answerList.value.push(anserValue.value)
   anserValue.value = ''
   showBtn.value = false



}
const cacelWindow = () => {
   anserValue.value = ''
   answerList.value = []
}
const addItem = () => {
   showBtn.value = true
}
// 地图选择
function submitMap() {
   openMap.value = false
   windowVisible.value = false;

   console.log(overlays.value, '9999', form.value.deptId);
   if (drawData.drawvalue === 'draw') {
      addByArr({
         plotData: JSON.stringify(overlays.value),
         deptId: form.value.deptId
      }).then(res => {
         if (drawData.drawtype === 'area' && drawData.drawvalue === 'draw') {
            areaPlotData.value = res.data
         } else if (drawData.drawtype === 'traffic' && drawData.drawvalue === 'draw') {
            unitPlotData.value = res.data
         }
         proxy.$modal.msgSuccess("绘制成功");
         openMap.value = false;
      });
   }


   console.log(overlays.value, 'overlays.value000');

   if (drawData.drawtype === 'area' && drawData.drawvalue === 'draw') { //
      areaPlotData.value = overlays.value
      form.value.areaName = form.value.deptName + '区域标绘'
   } else if (drawData.drawtype === 'traffic' && drawData.drawvalue === 'draw') {
      unitPlotData.value = overlays.value
      form.value.unitName = form.value.deptName + '交通标绘'
   } else if (drawData.drawtype === 'area' && drawData.drawvalue === 'text') {
      areaInfos.value[0].areaName = answerList.value.join(',')
   } else if (drawData.drawtype === 'traffic' && drawData.drawvalue === 'text') {
      unitInfos.value[0].unitName = answerList.value.join(',')
   }
}
// 关闭地图弹框
function cancelMap() {
   openMap.value = false
   windowVisible.value = false;

}
/**折叠展开*/
function handleExpend(type) {
   expend[type] = !expend[type]
}
/**选择地图*/
function handleSelete(type, value) {
   openMap.value = true
   answerList.value = []


   nextTick(() => {
      initMap(type, value)
   });
}
/*新增管辖区域、交通*/
function handleAddItem(type) {
   // 新增车辆
   console.log(deptCars, 'deptCars.value');
   deptCars.value.push({
      carName: "",
      licenseNumber: "",
      // frameNumber: "",
      carType: "",
      // equippingTime: "",
      // tradeId: "",
      handPump: "",
      carryingWater: "",
      foamContent: "",
      foamType: "",
      pumpFlow: "",
      liftingHeight: "",
      gunFlow: "",
      tractionPower: "",
      overhangPower: "",
      remark: '', //备注
      // vehicleEquipment: ""

   })
}
/** 查询部门类型 */
function listDataDept() {
   listData({
      pageNum: 1,
      pageSize: 100,
      dictType: "SYS_DEPT_TYPE",
   }).then((response) => {
      deptTypeList.value = response.rows;
      console.log(deptTypeList.value, 'deptTypeList');
   });
}
/** 查询站点类型 */
function listDataStation() {
   listData({
      pageNum: 1,
      pageSize: 100,
      dictType: "SYS_STATION_TYPE",
   }).then((response) => {
      stationTypeList.value = response.rows;
   });
}
/** 查询站点级别 */
function listDataAddr() {
   listData({
      pageNum: 1,
      pageSize: 100,
      dictType: "SYS_DEPT_LEVEL",
   }).then((response) => {
      deptLevelList.value = response.rows;
   });
}
/** 查询部门列表 */
function getList() {
   loading.value = true;
   listDept(queryParams.value).then(response => {
      deptList.value = proxy.handleTree(response.data, "deptId");
      loading.value = false;
   });
}
/*
查询车型*/
function listDataCart() {
   listData({
      pageNum: 1,
      pageSize: 100,
      dictType: "SYS_CART_TYPE",
   }).then((response) => {
      cartLevelList.value = response.rows;
   });
}
/*
查询泡沫类型*/
function listDataForm() {
   listData({
      pageNum: 1,
      pageSize: 100,
      dictType: "SYS_FOAM_TYPE",
   }).then((response) => {
      formLevelList.value = response.rows;
   });
}
/** 取消按钮 */
function cancel() {
   open.value = false;
   reset();
}
/** 表单重置 */
function reset() {
   form.value = {
      deptId: undefined,
      parentId: undefined,
      deptName: undefined,
      orderNum: 0,
      leader: undefined,
      phone: undefined,
      email: undefined,
      status: "0",
      deptType: '',
      deptLevel: '',
      stationType: '',
      address: '',
      longitude: '',
      latitude: ''
      // channel: undefined,
   };
   form3.value = {
      channel: ''
   };
   areaInfos.value = [{ // 部门辖区
      areaName: ''
   }]
   unitInfos.value = [{ // 交通辖区
      unitName: ''
   }]
   areaPlotData.value = []
   unitPlotData.value = []
   deptCars.value = [{
      carName: "", // 车辆名称
      carType: "", // 车型
      licenseNumber: "",//车牌号
      handPump: "", // 手抬泵数量
      carryingWater: "", //载水量
      foamContent: "", //泡沫量
      foamType: "", //泡沫类型
      pumpFlow: "", //泵流量
      liftingHeight: "", //举升高度
      gunFlow: "", //消防炮流量
      tractionPower: "", //牵引
      overhangPower: "", //吊机
      remark: '', //备注
   }]

   proxy.resetForm("deptRef");
}
/** 搜索按钮操作 */
function handleQuery() {
   getList();
}
/** 重置按钮操作 */
function resetQuery() {
   proxy.resetForm("queryRef");
   handleQuery();
}
/** 新增按钮操作 */
function handleAdd(row) {
   reset();
   listDept().then(response => {
      deptOptions.value = proxy.handleTree(response.data, "deptId");
   });
   if (row != undefined) {
      form.value.parentId = row.deptId;
   }
   open.value = true;
   title.value = "添加部门";
}
/** 展开/折叠操作 */
function toggleExpandAll() {
   refreshTable.value = false;
   isExpandAll.value = !isExpandAll.value;
   nextTick(() => {
      refreshTable.value = true;
   });
}
/** 修改按钮操作 */
function handleUpdate(row) {
   reset();
   getDept(row.deptId).then(response => {
      let data = response.data
      console.log(data, 'datadeptId');
      form.value.deptId = data.deptId;
      form.value.parentId = data.parentId;
      form.value.deptName = data.deptName;

      form.value.orderNum = data.orderNum;
      form.value.leader = data.leader;
      form.value.phone = data.phone;

      form.value.email = data.email;
      form.value.status = data.status;
      form.value.deptType = data.deptType;

      form.value.deptLevel = data.deptLevel;
      form.value.stationType = data.stationType;
      form.value.address = data.address;
      form.value.longitude = data.longitude

      form.value.latitude = data.latitude
      form.value.unitName = data.deptName + '区域绘制'
      form.value.areaName = data.deptName + '交通绘制'

      form3.value.channel = data.channel
      areaInfos.value = data.deptAreaVos && data.deptAreaVos.map(item => {
         return {
            id: item.id,
            deptId: item.deptId,
            areaName: item.areaName
         }
      })
      unitInfos.value = data.deptUnitVos && data.deptUnitVos.map(item => {
         return {
            id: item.id,
            deptId: item.deptId,
            unitName: item.unitName
         }
      })
      areaPlotData.value = JSON.parse(data.areaPlotData)
      unitPlotData.value = JSON.parse(data.unitPlotData)


      console.log(areaPlotData.value, '000areaPlotData.value');

      var result = data.deptCarVos && response.data.deptCarVos.map(item => {
         return {
            id: item.id,
            carName: item.carName,
            carType: item.carType,
            licenseNumber: item.licenseNumber,
            handPump: item.handPump,
            carryingWater: item.carryingWater,
            foamContent: item.foamContent,
            foamType: item.foamType,
            pumpFlow: item.pumpFlow,
            liftingHeight: item.liftingHeight,
            gunFlow: item.gunFlow,
            tractionPower: item.tractionPower,
            overhangPower: item.overhangPower,
            remark: item.remark //备注
         }
      })
      deptCars.value = result || [{
         carName: "", // 车辆名称
         carType: "", // 车型
         licenseNumber: "",//车牌号
         handPump: "", // 手抬泵数量
         carryingWater: "", //载水量
         foamContent: "", //泡沫量
         foamType: "", //泡沫类型
         pumpFlow: "", //泵流量
         liftingHeight: "", //举升高度
         gunFlow: "", //消防炮流量
         tractionPower: "", //牵引
         overhangPower: "", //吊机
         remark: '', //备注
      }]
      open.value = true;
      title.value = "修改部门";
      listDeptExcludeChild(row.deptId).then(response => {
         deptOptions.value = proxy.handleTree(response.data, "deptId");
         if (deptOptions.value.length == 0) {
            const noResultsOptions = { deptId: form.value.parentId, deptName: form.value.parentName, children: [] };
            deptOptions.value.push(noResultsOptions);
         }
      });
   });
}
/** 提交按钮 */
function submitForm() {
   proxy.$refs["deptRef"].validate(valid => {
      if (valid) {

         let params = {
            ...form.value,
            ...form3.value,
            deptArea: {
               areaInfos: areaInfos.value
            },
            deptUnit: {
               unitInfos: unitInfos.value
            },
            deptCars: deptCars.value,
            unitPlotData: unitPlotData.value,
            areaPlotData: areaPlotData.value
         }

         if (form.value.deptId != undefined) {
            updateDept(params).then(response => {
               proxy.$modal.msgSuccess("修改成功");
               open.value = false;
               getList();
            });
         } else {
            console.log(answerList.value, '---answerList11');
            console.log(unitPlotData.value, '---1122', areaPlotData.value);
            console.log(form.value, form3.value, '---11', areaInfos.value, '---11', unitInfos.value, '---11', deptCars.value);
            // let params = {
            //    ...form.value,
            //    ...form3.value,
            //    deptArea: {
            //       areaInfos: areaInfos.value
            //    },
            //    deptUnit: {
            //       unitInfos: unitInfos.value
            //    },
            //    deptCars: deptCars.value,
            //    unitPlotData: JSON.stringify(unitPlotData.value),
            //    areaPlotData: JSON.stringify(areaPlotData.value)
            // }
            console.log(params, '---params');
            addDept(params).then(response => {
               proxy.$modal.msgSuccess("新增成功");
               open.value = false;
               getList();
            });
         }
      }
   });
}
function handleCart() {
   openCart.value = true
   console.log(deptCars.value, 'deptCars');
}
// 提交车辆信息弹框
function submitCart() {
   openCart.value = false
}
// 关闭车辆信息弹框
function cancelCart() {
   openCart.value = false
}
/** 删除按钮操作 */
function handleDelete(row) {
   proxy.$modal.confirm('是否确认删除名称为"' + row.deptName + '"的数据项?').then(function () {
      return delDept(row.deptId);
   }).then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
   }).catch(() => { });
}

getList();
listDataDept()
listDataStation()
listDataAddr()
listDataCart()
listDataForm()
</script>
<style lang="scss">
#container {
   width: 100%;
   height: 500px;
}

.amap-sug-result {
   z-index: 9999 !important;
}

.inputBox {
   height: 50px;
   line-height: 30px;
   display: flex;
   width: 500px;

   input {
      border: 1px solid #d3d3d3;
      width: 400px;
      height: 30px;
      padding: 4px;
      outline: none;
      border-radius: 4px;
   }

}

.windowBox {
   width: 30%;
   align-self: flex-start;
   background-color: #fff;
   position: absolute;
   top: 20%;
   left: 20%;
   cursor: pointer;
   border-radius: 16px 16px 16px 16px;
   z-index: 9999;

   .title {
      width: 100%;
      height: 30px;
      background: #2B5AA2;
      line-height: 30px;
      color: #fff;
      padding-left: 10px;
      box-sizing: border-box;
      font-size: 16px;
      border-radius: 16px 16px 0 0;
   }

   .el-input {
      margin-right: 10px;
      margin-left: 10px;
   }

   .item {
      padding: 6px;
      color: #4E5969;
      display: flex;
      justify-content: space-between;

      .close {
         color: #2B5AA2;
      }
   }

   .btnBox {
      display: flex;
      border-top: 1px solid #ddd;
      padding: 10px 0;

      el-input {
         height: 200px;
         height: 36px;
         margin-right: 10px;
      }
   }

   .addBtn {
      padding: 5px;
      cursor: pointer;
      color: #0084ce;
   }
}

.mark {
   text-align: center;
   color: #189C3F;
}

.dialog_box {
   height: 600px;
   overflow-y: scroll;

   .dept_box {
      .cartBox {
         display: flex;
         // justify-content:;
         align-items: center;
      }

      .btnright {
         color: #2B5AA2;
         font-size: 12px;
         margin-left: 30px;
      }

      .title {
         color: #333333;
         display: flex;
         align-items: center;
         margin: 15px 0;
         cursor: pointer;

         &::before {
            display: inline-block;
            content: '';
            width: 2px;
            height: 18px;
            background-color: #2B5AA2;
            margin-right: 10px;
         }
      }

      .title1 {
         margin-left: 20px;
         font-size: 12px;
      }

      .inputFlex {
         display: flex;
         align-items: baseline;

         span {
            cursor: pointer;
         }
      }

      span {
         cursor: pointer;
      }
   }

}
</style>
